import {
  DeleteOutlined} from "@ant-design/icons";
import React, { useState, useRef, useEffect, useContext } from 'react';
import { ProColumns, ProTable, TableDropdown, ActionType } from '@ant-design/pro-components';
import { Button, Table, Space, Card, Modal } from 'antd';
import './index.css'
import { GroupListFileds, APGroupTableListItem } from './data';
import GroupDrawer from "./GroupDrawer";
import DevSettingTabs from "./DevSettingTabs";
import { http_request, ac_cgi_url } from "@src/Common/Request";
import { AllContext,CreateProviderContextInstance } from '@src/Common/AllContext';
import AddDeviceDrawer from './AddDeviceDrawer';
import DevListView from './DevListView';

const expandedRowRender = (record: APGroupTableListItem) => {
  return (
    <Card>
      <DevListView groupId={record.groupId} />
    </Card>
  );
};

export default () => {
  const { tabName, tabKey, isReload, setIsReload, devType, messageApi } = useContext(AllContext);
  const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>([]);
  const actionRef = useRef<ActionType>();
  const baseContext = useContext(AllContext);
  const deleteGroupById = (groupIds: any) => {
    if (groupIds === undefined || groupIds === null) {
      messageApi.warning('groupIds is undefined or null ,please select ids first');
      return;
    }

    // if groupIds is string, it's alone delete one group, then will be [groupIds]
    if (typeof groupIds === 'string') {
      groupIds = [groupIds];
    }

    const values = {
      devType: devType,
      groupIds: groupIds
    }
    http_request(
      ac_cgi_url,
      values,
      'DELETE',
      {},
    ).then(responseObject => {
      if (!responseObject.success) {
        messageApi.warning(responseObject.msg);
      }else{
        messageApi.success(responseObject.msg);
      }
      setIsReload(true);
      return responseObject.data;
    });
  };

  const multiDeleteGroupById = (record: any) => {
    if (record.length === 0) {
      messageApi.warning('groupIds is undefined or null ,please select ids first');
      return;
    }
    deleteGroupById(record);
  };

  const set_actions_by_group = async (action: string, groupId: string) => {
    if (!groupId) {
      messageApi.warning('分组ID不能为空');
      return;
    }
  
    // 根据操作类型显示确认对话框
    let confirmTitle = "确认操作";
    let confirmContent = "";
    let apiAction = "";
    
    switch (action) {
      case "allRestart":
        confirmTitle = "确认重启";
        confirmContent = `您确定要重启分组 "${groupId}" 中的所有设备吗？`;
        apiAction = "restart";
        break;
      case "allReset":
        confirmTitle = "确认恢复出厂";
        confirmContent = `您确定要将分组 "${groupId}" 中的所有设备恢复出厂设置吗？此操作不可撤销！`;
        apiAction = "reset";
        break;
      case "allUprade": // 注意：原代码中的拼写是"allUprade"
        confirmTitle = "确认升级";
        confirmContent = `您确定要升级分组 "${groupId}" 中的所有设备吗？`;
        apiAction = "upgrade";
        break;
      default:
        messageApi.warning('未知的操作类型');
        return;
    }
  
    Modal.confirm({
      title: confirmTitle,
      content: confirmContent,
      onOk: async () => {
        try {
          const values = {
            devType: devType,
            action: 'set_actions_by_group',
            groupId: groupId,
            dev_action: apiAction,
          };
  
          const responseObject = await http_request(
            ac_cgi_url,
            values,
            "POST",
            {}
          );
  
          if (!responseObject.success) {
            messageApi.warning(responseObject.msg || "操作失败");
          } else {
            messageApi.success(responseObject.msg || "操作成功");
            // 操作成功后刷新表格
            setIsReload(true);
          }
        } catch (error) {
          messageApi.error("操作过程发生错误");
        }
      },
    });
  };

  // Add option for more aciton colum
  const columns: ProColumns<APGroupTableListItem>[] = [
    ...GroupListFileds,
    {
      title: '操作',
      dataIndex: 'operation',
      valueType: 'option',
      render: (value: any, record: any, index: number) => {
        let isDisableDelete =  false;
        if(record.groupId === "default")
          isDisableDelete = true;
        return <Space>
          {CreateProviderContextInstance(baseContext, {groupActionDrawer: 'add_dev', group: record }, AddDeviceDrawer)}
          <a hidden={isDisableDelete} onClick={() => deleteGroupById(record.key)}>删除</a>
          {CreateProviderContextInstance(baseContext, {groupActionDrawer: 'edit', group: record }, GroupDrawer)}
          <a onClick={() => {
            setExpandedRowKeys(expandedRowKeys.includes(record.key) ? 
              expandedRowKeys.filter(k => k !== record.key) : 
              [...expandedRowKeys, record.key]);
          }}>查看设备</a>
          <TableDropdown
            key="actionGroup"
            menus={[
              // { key: 'setDefaultGroup', name: '设为默认组' },
              { key: 'allRestart', name: '重启设备' },
              { key: 'allReset', name: '恢复出厂' },
              { key: 'allUprade', name: '升级设备' },
            ]}
            onSelect={(key) => set_actions_by_group(key, record.groupId)}
          >更多</TableDropdown>
        </Space>
      }
    },
  ];

  useEffect(() => {
    if (isReload && actionRef.current) {
      actionRef.current?.reload();
      setIsReload(false);
    }
  }, [isReload]);

  return (
    <>
      <ProTable<APGroupTableListItem>
        size='small'
        columns={columns}
        request={(params, sorter, filter) => {
          const request_params = new URLSearchParams();
          request_params.set("devType", tabKey);
          return http_request(
            `${ac_cgi_url}?${request_params}`,
            null,
            'GET',
            {},
          ).then(responseObject => {
            const data = responseObject.data;
            // for group list
            const groupList = [];
            for (let i = 0; i < data.length; i++) {
              const group = data[i].group;
              groupList.push({
                key: group.groupId,
                ...group,
              });
            }
            if (!responseObject.success) {
              messageApi.warning(responseObject.msg);
            }
            return Promise.resolve({
              data: groupList,
              success: true,
            });
          });
        }}
        rowKey="key"
        rowSelection={{
          selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
          getCheckboxProps: (record: any) => ({
            disabled: record.groupId === "default"
          })
        }}
        pagination={{
          pageSize: 8,
          showQuickJumper: true,
        }}
        options={{
          density: true,
          setting: true,
        }}
        expandable={{ 
          expandedRowRender, 
          expandedRowKeys, 
          onExpandedRowsChange: keys => setExpandedRowKeys(keys as React.Key[]) 
        }}
        search={false}
        bordered={false}
        actionRef={actionRef}
        dateFormatter="string"
        headerTitle=<span className="GroupTitle">{tabName}</span>
        toolBarRender={(keys: any, record: any) => [
          CreateProviderContextInstance(baseContext, {groupActionDrawer: 'add', group: record }, GroupDrawer),
          <Button
            key="DeleteGroup"
            type="primary"
            size="small"
            className="DangerButton"
            onClick={() => {
              multiDeleteGroupById(record.selectedRowKeys);
            }}
          >
            删除分组
            <DeleteOutlined />
          </Button>,
        ]}
      />
    </>
  );
};
